package com.quick.develop.flowable.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.quick.develop.framework.utils.DateUtils;
import com.quick.develop.flowable.framework.cmd.ComplementHistoricTaskCmd;
import com.quick.develop.flowable.framework.factory.FlowServiceFactory;
import com.quick.develop.flowable.schedule.core.BpmScheduleHandler;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

import static com.quick.develop.framework.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * desc: 补全已办数据
 *
 * @author junyuan.liu
 * @date 2023/12/28 8:41
 */
@Slf4j
@Component
public class BpmComplementHisTask extends FlowServiceFactory implements BpmScheduleHandler {

    @Value("${flowable.custom.comp-histask.before-time:#{null}}")
    @DateTimeFormat(pattern = YYYY_MM_DD_HH_MM_SS)
    private Date beforeTime;


    @Override
    public void execute() {

        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .finished().withoutScopeId()
                .orderByHistoricTaskInstanceEndTime().desc()
                .list();

        for (HistoricTaskInstance task : list) {
            if (ObjectUtil.isNotNull(beforeTime)) {
                Date localDate = DateUtils.toDate(LocalDate.now());
                if (localDate.compareTo(beforeTime)  == 0){
                    break;
                }
            }
            managementService.executeCommand(new ComplementHistoricTaskCmd(task.getId()));
        }

    }
}
